<template>
  <div class="preview fit">
    <!-- 缩放层 -->
    <div
      ref="previewRef"
      class="preview-scale"
    >
      <!-- 展示层 -->
      <div
        v-if="show"
        :style="previewRefStyle"
      >
        <!-- 渲染层 -->
        <PreviewRender />
      </div>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import store from '@/store/modules/chartEdit'
import throttle from 'lodash/throttle'
import { mapGetters } from 'vuex'
import { fetchChartComponent } from '@/packages'
import PreviewRender from './components/PreviewRender'
import { getFilterStyle } from '@/utils'
export default {
  components: { PreviewRender },
  computed: {
    ...mapGetters(['componentList', 'editCanvasConfig']),
    previewRefStyle () {
      return {
        overflow: 'hidden',
        ...this.getEditCanvasConfigStyle(this.editCanvasConfig),
        ...getFilterStyle(this.editCanvasConfig)
      }
    }
  },
  data () {
    return {
      show: false,
      key: Date.now()
    }
  },
  methods: {
    // 渲染图表
    initChart () {
      if (Vue.component) {
        const intComponent = (target) => {
          if (!Vue.component[target.chartConfig.chartKey]) {
            Vue.component(target.chartConfig.chartKey, fetchChartComponent(target.chartConfig))
          }
        }
        this.componentList.forEach((e) => {
          intComponent(e)
        })
        this.show = true
      }
    },
    // 全局样式
    getEditCanvasConfigStyle (canvas) {
      // 背景
      const computedBackground = canvas.selectColor
        ? { background: canvas.background }
        : {
          background: `url(${canvas.backgroundImage}) center center / cover no-repeat !important`
        }
      return {
        position: 'relative',
        width: canvas.width ? `${canvas.width || 100}px` : '100%',
        height: canvas.height ? `${canvas.height}px` : '100%',
        ...computedBackground
      }
    },
    // 监听鼠标滚轮 +ctrl 键
    addWheelHandle () {
      addEventListener('wheel', (e) => {
        if (window?.$KeyboardActive?.ctrl) {
          e.preventDefault()
          e.stopPropagation()
          window.removeEventListener('resize', throttle(() => {
            this.calcRate()
          }, 200))
          const transform = this.$refs.previewRef?.style.transform
          const regRes = transform.match(/scale\((\d+\.?\d*)*/)
          const width = regRes[1]
          const previewBoxDom = document.querySelector('.preview')
          if (previewBoxDom) {
            previewBoxDom.style.overflow = 'unset'
            previewBoxDom.style.position = 'absolute'
          }
          if (e.wheelDelta > 0) {
            const resNum = parseFloat(Number(width).toFixed(2))
            this.$refs.previewRef.style.transform = `scale(${resNum > 5 ? 5 : resNum + 0.1})`
          } else {
            const resNum = parseFloat(Number(width).toFixed(2))
            this.$refs.previewRef.style.transform = `scale(${resNum < 0.2 ? 0.2 : resNum - 0.1})`
          }
        }
      },
        { passive: false }
      )
    },
    // 处理缩放
    calcRate () {
      // 当前屏幕宽高比
      let { width, height } = this.editCanvasConfig
      let currentRate = parseFloat(
        (window.innerWidth / window.innerHeight).toFixed(5)
      )
      let baseProportion = parseFloat(width / height).toFixed(5)
      let dom = this.$refs.previewRef
      // * 默认缩放值
      let scale = {
        width: 1,
        height: 1,
      }
      if (dom) {
        if (currentRate > baseProportion) {
          // 表示更宽
          scale.width = parseFloat(((window.innerHeight * baseProportion) / width).toFixed(5))
          scale.height = parseFloat((window.innerHeight / height).toFixed(5))
          dom.style.transform = `scale(${scale.width}, ${scale.height})`
        } else {
          // 表示更高
          scale.height = parseFloat(((window.innerWidth / baseProportion) / height).toFixed(5))
          scale.width = parseFloat((window.innerWidth / width).toFixed(5))
          dom.style.transform = `scale(${scale.width}, ${scale.height})`
        }
      }
    },
    // 获取存储数据的信息
    getSessionStorageInfo(){
      let storageList=JSON.parse(sessionStorage.getItem('chartList'))
      const { editCanvasConfig, componentList } = storageList[0]
        store.state.editCanvasConfig = editCanvasConfig
        store.state.componentList = componentList
        return storageList[0]
    }
  },
  mounted () {
    document.title = '预览'
    this.getSessionStorageInfo()
    this.calcRate()
    // * 改变窗口大小重新绘制
    window.addEventListener('resize', throttle(() => {
      this.calcRate()
    }, 200))
    this.addWheelHandle()
    this.initChart()
  },
  destroyed () {
    window.removeEventListener('resize', throttle(() => {
      this.calcRate()
    }, 200))
  }
}
</script>

<style lang="scss" scoped>
.preview {
  position: relative;
  height: 100vh;
  width: 100vw;
  // background-image: linear-gradient(120deg, #18181c 0%, #18181c 100%);
  &.fit,
  &.full {
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    .preview-scale {
      transform-origin: center center;
    }
  }
  &.scrollY {
    overflow-x: hidden;
    .preview-scale {
      transform-origin: left top;
    }
  }
  &.scrollX {
    overflow-y: hidden;
    .preview-scale {
      transform-origin: left top;
    }
  }
  .go-preview-entity {
    overflow: hidden;
  }
}
</style>